﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using NLog;

namespace Gollie.Payment.Targetpay
{
	public class BankWire : IDeal
	{
		public BankWire(string partnerId, string description, int amount, string reporturl, string returnurl, bool test=false)
			: base(test)
		{
			string salt = ConfigAppSettings.GetValue("wiresalt");
			string ip = ObjectFormatter.CurrentIp;

			if (ip == null)
				return;

			Dictionary<string, string> args = new Dictionary<string, string>();

			args["rtlo"] = partnerId;
			args["description"] = description;
			args["amount"] = amount.ToString("#0");
			args["userip"] = ip;
			args["reporturl"] = reporturl;
			args["salt"] = salt;
			args["returnurl"] = returnurl;

			logger.Debug("Amount: {0}", args["amount"]);

			this.ProcessRequest(this.kenmerkUrl, args);
		}

		protected override void ProcessTargetPayResponse(string response)
		{
			if (response == null)
				throw new Exception("response is null");

			try
			{
				string returnCode = response.Substring(0, 6);
				if (returnCode != "000000")
				{
					this.LogReturnCode(returnCode);
					throw new Exception("Bankwire start error: " + returnCode);
				}

				string[] args = response.Substring(7).Split('|');

				Kenmerk = args[0];
				string rknr = args[1];
				IbanRknr = args[2];
				string bic = args[3];
				TenaamStelling = args[4];
				string bank = args[5];
			}
			catch (Exception e)
			{
				throw new Exception("Error parsing response: '" + response + "'", e);
			}
		}

		public string Kenmerk { get; private set; }
		public string IbanRknr { get; private set; }
		public string TenaamStelling { get; private set; }
	}
}